<template>
    <Form ref="phoneLoginForm" :model="phoneLoginForm" :rules="ruleValidate" @keydown.enter.native="handleSubmit">
        <FormItem prop="phoneNumber">
            <Input type="text" size="large" v-model="phoneLoginForm.phoneNumber" clearable placeholder="手机号" autocomplete="off">
                <Icon type="md-phone-portrait" slot="prefix" />
            </Input>
        </FormItem>
        <FormItem prop="verificationCode">
            <Input class="code-input" type="text" size="large" v-model="phoneLoginForm.verificationCode" placeholder="短信验证码" autocomplete="off">
                <Icon custom="iconfont icon-yanzhengma" slot="prefix" />
                <Button slot="append" :disabled="phoneNumberInvalid">获取短信验证码</Button>
            </Input>
        </FormItem>
    </Form>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'PhoneLoginForm',
  data () {
    const customPhoneNumberRules = (rule, value, callback) => {
      if (value === '') {
        this.changeDataValid(false)
        this.phoneNumberInvalid = true
        callback(new Error('手机号不能为空'))
      } else if (!(/^1[34578]\d{9}$/.test(value))) {
        this.changeDataValid(false)
        this.phoneNumberInvalid = true
        callback(new Error('手机号格式不正确'))
      } else {
        this.changeDataValid(true)
        this.phoneNumberInvalid = false
        callback()
      }
    }
    const customVerificationCodeRules = (rule, value, callback) => {
      if (value === '') {
        this.changeDataValid(false)
        callback(new Error('短信验证码不能为空'))
      } else {
        this.changeDataValid(true)
        callback()
      }
    }
    return {
      phoneNumberInvalid: true,
      phoneLoginForm: {
        phoneNumber: '',
        verificationCode: ''
      },
      ruleValidate: {
        phoneNumber: [{
          validator: customPhoneNumberRules,
          trigger: 'blur'
        }],
        verificationCode: [{
          validator: customVerificationCodeRules,
          trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    ...mapActions([
      'changeDataValid' // 将 `this.changeDataValid(status)` 映射为 `this.$store.dispatch('changeDataValid',status)`
    ]),
    handleSubmit () {
      this.$refs.phoneLoginForm.validate(valid => {
        if (valid) {
          this.$emit('on-success-valid', {
            phoneNumber: this.phoneLoginForm.phoneNumber,
            verificationCodeRules: this.phoneLoginForm.verificationCodeRules
          })
        }
      })
    }
  }
}
</script>

<style lang="less">
    .code-input {
        .ivu-input-prefix {
            z-index: 2;
        }
        .ivu-input-with-prefix {
            padding-left: 32px;
        }
    }
</style>
